<template>
  <div class="edit">
      <el-card shadow="never">
        <el-page-header @back="cancel" :content="prop.title"></el-page-header>
      </el-card>
      <el-card shadow="never">
        <div>| 基本信息</div>
        <el-form ref="form" :model="form" :rules="rules" label-width="160px" label-position="right">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item class="archives-photo-form-item">
                <el-upload
                  class="avatar-upload"
                  list-type="picture-card"
                  :action="getAllAction"
                  :on-remove="delFile"
                  :headers="headers"
                  :before-upload="handleBeforeUpload"
                  :on-success="archivesUploadSuccess"
                  :on-error="handleUploadError"
                  :limit="1"
                  :show-file-list="false"
                  :file-list="archivesPhotoList"
                >
                  <img v-if="archivesPhotoSrc" :src="archivesPhotoSrc" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="中文姓名" prop="employeeName">
                <el-input v-model="form.employeeName" placeholder="2-20个汉字"></el-input>
              </el-form-item>
              <el-form-item label="籍贯" prop="employeeNative">
                <el-cascader
                  v-model="form.employeeNative"
                  :options="natives"
                  :props="nativesProps"
                  filterable
                  placeholder="请选择籍贯"
                  class="custome-form-item-width"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="出生日期" prop="employeeBirthday">
                <el-date-picker
                  v-model="form.employeeBirthday"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择出生日期"
                  class="custome-form-item-width"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="民族" prop="employeeNation">
                <el-select v-model="form.employeeNation" placeholder="请选择民族" class="custome-form-item-width" filterable>
                  <el-option v-for="(nation,index) in nations" :key="nation.value" :label="nation.label" :value="nation.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="户籍类型" prop="employeeRegisteredType">
                <el-select v-model="form.employeeRegisteredType" placeholder="请选择户籍类型" class="custome-form-item-width" >
                  <el-option label="农村户口" value="0"></el-option>
                  <el-option label="城镇居民户口" value="1"></el-option>
                  <el-option label="集体户口" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="入职日期" prop="employeeJoinTime">
                <el-date-picker
                  v-model="form.employeeJoinTime"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择入职日期"
                  class="custome-form-item-width"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号码" prop="employeeTel">
                <el-input v-model="form.employeeTel" placeholder="手机号"></el-input>
              </el-form-item>
              <el-form-item label="户籍所在地" prop="employeeRegisteredResidence">
                <el-input v-model="form.employeeRegisteredResidence" placeholder="户籍所在地"></el-input>
              </el-form-item>
              <el-form-item label="首次参加工作日期" prop="employeeFirstJobTime">
                <el-date-picker
                  v-model="form.employeeFirstJobTime"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择首次参加工作日期"
                  class="custome-form-item-width"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="性别" prop="employeeGender">
                <el-radio-group v-model="form.employeeGender">
                  <el-radio label="0">男</el-radio>
                  <el-radio label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="聘用类型" prop="employeeEmployType">
                <el-select v-model="form.employeeEmployType" placeholder="请选择聘用类型" class="custome-form-item-width" >
                  <el-option label="内聘"value="0"></el-option>
                  <el-option label="外聘"value="1"></el-option>
                  <el-option label="返聘"value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="编制类型" prop="employeeInHeadship">
                <el-select v-model="form.employeeInHeadship" placeholder="请选择编制类型" class="custome-form-item-width" >
                  <el-option label="非事业编制"value="0"></el-option>
                  <el-option label="事业编制"value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="聘用形式" prop="employeeEmployForm">
                <el-select v-model="form.employeeEmployForm" clearable placeholder="请选择" class="custome-form-item-width" >
                  <el-option label="全职" value="0"></el-option>
                  <el-option label="兼职" value="1"></el-option>
                  <el-option label="临时" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="开户银行" prop="employeeBankName">
                <el-input v-model="form.employeeBankName" placeholder="1-30字符"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行卡号" prop="employeeBankCard">
                <el-input v-model="form.employeeBankCard" placeholder="15-20位数字"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="身高(cm)" prop="employeeHeight">
                <el-input v-model="form.employeeHeight" placeholder="120-230cm"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="体重(KG)" prop="employeeWeight">
                <el-input v-model="form.employeeWeight" placeholder="30-250KG"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="婚育情况" prop="employeeMaritalStatus">
                <el-select v-model="form.employeeMaritalStatus" placeholder="请选择婚育情况" class="custome-form-item-width" >
                  <el-option label="未婚" value="0"></el-option>
                  <el-option label="已婚未育" value="1"></el-option>
                  <el-option label="已婚已育" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="身份证号" prop="employeeIdcard">
                <el-input v-model="form.employeeIdcard" placeholder="18位字符"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="个人邮箱" prop="employeeEmail">
                <el-input v-model="form.employeeEmail" placeholder="1-30字符"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否双师" prop="employeeIsTutor">
                <el-select v-model="form.employeeIsTutor" placeholder="请选择是否双师" class="custome-form-item-width" >
                  <el-option label="否" value="0"></el-option>
                  <el-option label="是" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="紧急联系人1" prop="employeeEmergencyOnePerson">
                <el-input v-model="form.employeeEmergencyOnePerson" placeholder="1-10汉字"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="紧急联系人1电话号码" prop="employeeEmergencyOneTel">
                <el-input v-model="form.employeeEmergencyOneTel" placeholder="11位数字"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="紧急联系人2" prop="employeeEmergencyTwoPerson">
                <el-input v-model="form.employeeEmergencyTwoPerson" placeholder="1-10汉字"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="紧急联系人2电话号码" prop="employeeEmergencyTwoTel">
                <el-input v-model="form.employeeEmergencyTwoTel" placeholder="11位数字"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="政治面貌" prop="employeeParty">
                <el-select v-model="form.employeeParty" placeholder="请选择政治面貌" class="custome-form-item-width" filterable>
                  <el-option v-for="(party,index) in parties" :key="party.value" :label="party.label" :value="party.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="英文姓名" prop="employeeEnglishName">
                <el-input v-model="form.employeeEnglishName" placeholder="1-30字母"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="其它身份证件类型" prop="employeeCertificateTypeId">
                <el-select v-model="form.employeeCertificateTypeId" clearable placeholder="请选择证件类型" class="custome-form-item-width" >
                  <el-option v-for="(type,index) in otherIdentityTypes" :key="type.raw.dictCode" :label="type.raw.dictLabel" :value="type.raw.dictCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="其它身份证件号码" prop="employeeCertificateCode">
                <el-input v-model="form.employeeCertificateCode" placeholder="请输入证件号码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="转正日期" prop="employeeFormalTime">
                <el-date-picker
                  v-model="form.employeeFormalTime"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择转正日期"
                  class="custome-form-item-width"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="身份证照片">
                <el-upload
                  list-type="picture-card"
                  :action="getAllAction"
                  :on-remove="delFile"
                  :headers="headers"
                  :before-upload="handleBeforeUpload"
                  :on-success="idcardUploadSuccess"
                  :on-error="handleUploadError"
                  :limit="2"
                  :file-list="idcardFileList"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}" class="upload-slot-img">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.filePath" alt="" object-fit="fill"
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="delFile(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="form.employeeCertificateTypeId && form.employeeCertificateCode">
            <el-col :span="24">
              <el-form-item label="其它身份证件照片">
                <el-upload
                  list-type="picture-card"
                  :action="getAllAction"
                  :on-remove="delFile"
                  :headers="headers"
                  :before-upload="handleBeforeUpload"
                  :on-success="otherUploadSuccess"
                  :on-error="handleUploadError"
                  :limit="2"
                  :file-list="otherCertificateFileList"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}" class="upload-slot-img">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.filePath" alt="" object-fit="fill"
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="delFile(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <div>| 任职信息</div><!--需要处理本校岗位重复情况-->
          <div v-for="(item,index) in form.employeePosts" class="hold-post-container">
            <el-row :gutter="5">
              <el-col :span="5">
                <el-form-item
                label="任职组织"
                label-width="60"
                :prop="'employeePosts.' + index + '.organizationSysCode'"
                :rules="[
                  { required: true, message: '请选择任职组织', trigger: 'change' },
                ]"
                >
                  <Treeselect
                    v-model="item.organizationSysCode"
                    :options="organizations"
                    :flat="true"
                    :multiple="false"
                    :normalizer="normalizer"
                    @input="organizationChange"
                    placeholder="请选择适用组织"
                    noOptionsText="暂无数据">
                  </Treeselect>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                label="任职岗位"
                label-width="60"
                :prop="'employeePosts.' + index + '.postSysCode'"
                :rules="[
                  { required: true, message: '请选择任职岗位', trigger: 'change' },
                ]">
                  <el-select v-model="item.postSysCode" clearable placeholder="请选择任职岗位" style="width:100%" @change="postChange">
                    <el-option
                      v-for="item in posts"
                      :key="item.postSysCode"
                      :label="item.postSysPath"
                      :value="item.postSysCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item
                label="岗位职级"
                label-width="60"
                :prop="'employeePosts.' + index + '.gradeId'"
                :rules="[
                  { required: true, message: '请选择岗位职级', trigger: 'change' },
                ]">
                  <el-select v-model="item.gradeId" clearable placeholder="请选择岗位职级">
                    <el-option
                      v-for="item in grades"
                      :key="item.gradeId"
                      :label="item.gradeName"
                      :value="item.gradeId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item
                label="任职时间"
                label-width="60"
                :prop="'employeePosts.' + index + '.startTime'"
                :rules="[
                  { required: true, message: '请选择任职时间', trigger: 'change' },
                ]">
                  <el-date-picker
                    v-model="item.startTime"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="选择任职时间"
                    class="custome-form-item-width"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="employee-post-operator">
                <el-form-item label-width="30">
                  <div v-if="form.employeePosts.length>1 && index===(form.employeePosts.length-1)">
                    <el-button type="danger" circle icon="el-icon-delete" @click="delEmployeePost(index)"></el-button>
                    <el-button circle icon="el-icon-plus" @click="addEmployeePost"></el-button>
                  </div>
                  <div v-else-if="form.employeePosts.length>1 && index!==(form.employeePosts.length-1)">
                    <el-button type="danger" circle icon="el-icon-delete" @click="delEmployeePost(index)"></el-button>
                  </div>
                  <div v-else>
                    <el-button circle icon="el-icon-plus" @click="addEmployeePost"></el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-dialog
          :visible="showUploadArchivesPhoto"
          title="上传证件照"
          class="upload-archives-container"
          @close="closeArchivesUpload()"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :modal="false"
          destroy-on-close
        >
          <el-upload
            list-type="picture-card"
            :action="getAllAction"
            :on-remove="delFile"
            :headers="headers"
            :before-upload="handleBeforeUpload"
            :on-success="archivesUploadSuccess"
            :on-error="handleUploadError"
            :limit="1"
            :file-list="archivesPhotoList"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}" class="upload-slot-img">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.filePath" alt="" object-fit="fill"
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="delFile(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-dialog>
        <div>
          <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-card>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getOrganizationsSelectItems} from '@/api/organization/organization/organization.js'
import {getPostSelectItemsByOrganization} from '@/api/organization/post/post.js'
import {getGradeSelectItemsByPost} from '@/api/organization/grade/grade.js'
import {getProvinceCitySelectItems,add,edit,getDetail} from '@/api/employee/employee/employee.js'
import {uploadUrl,uploadAndGetFileAllUrl,uploadHeaders,echoPrefix,download,deleteFile} from '@/api/file/file.js'
import {luhnCheck,idCardNoUtil} from '@/utils/collegeHrSystemUI.js'
import {parties,nations,certificateCategory} from '@/utils/constants/common/constants.js'
export default {
  name: "EmployeeEdit",
  components:{Treeselect},
  dicts:['idcard_certificate_type'],
  props:{
    prop:{
      type:Object,
      default:function(){
        return {
          open:false,
          title:'新增人员',
          employeeId:null,
        }
      }
    }
  },
  computed:{
    otherIdentityTypes:function () {
      if(this.dict.type.idcard_certificate_type){
        return this.dict.type.idcard_certificate_type.filter(item =>item.value !== 'idcard')
      }
    }
  },
  data(){
    var telValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        let telRex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (telRex.test(value)) {
          return callback()
        }else{
          return callback(new Error('请输入正确的手机号码'));
        }
      }else if(rule.required){
         return callback(new Error('请输入正确的手机号码'));
      }else{
        return callback()
      }
    };
    var emailValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        let telRex = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        if (telRex.test(value)) {
          return callback()
        }else{
          return callback(new Error('请输入正确的邮箱地址'));
        }
      }else{
         return callback(new Error('请输入正确的邮箱地址'));
      }
    };
    var bankCardValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        if (luhnCheck(value)) {
          return callback()
        }else{
          return callback(new Error('请输入正确的银行卡号'));
        }
      }else{
         return callback(new Error('请输入正确的银行卡号'));
      }
    };
    var idcardValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        if (idCardNoUtil.checkIdCardNo(value)) {
          return callback()
        }else{
          return callback(new Error('请输入正确的身份证号'));
        }
      }else{
         return callback(new Error('请输入正确的身份证号'));
      }
    };
    var numValidator = (rule, value, callback) => {
      value = value+""//处理回显数据类型错误问题
      let field = rule.field
      let valNum = Number.parseInt(value)
      if (field==='employeeHeight'){
        if(value===undefined|| value===null||value.trim()===""){
          return callback(new Error('请输入合理的身高'));
        }else if(Number.isInteger(valNum) && valNum>=120 && valNum<=230) {
          return callback()
        }else{
          return callback(new Error('请输入合理的身高'));
        }
      }else if(field==='employeeWeight'){
        if(value===undefined|| value===null||value.trim()===""){
          return callback(new Error('请输入合理的体重'));
        }else if(Number.isInteger(valNum)&& valNum>=30 && valNum<=250) {
          return callback()
        }else{
          return callback(new Error('请输入合理的体重'));
        }
      }
    };
    return{
      saveLoading:false,
      nativesProps:{
        value:'provinceCityCountyCode',
        label:'provinceCityCountyName',
        children:'children',
        emitPath:false,
      },
      natives:[],
      organizations:[],
      posts:[],
      grades:[],
      parties:parties,
      nations:nations,
      certificateCategory:certificateCategory,
      showUploadArchivesPhoto:false,
      archivesPhotoSrc:null,
      form: {
        employeeName:null,
        employeeEnglishName:null,
        employeeNative:null,
        employeeBirthday:null,
        employeeRegisteredType:null,
        employeeJoinTime:null,
        employeeTel:'',
        employeeRegisteredResidence:null,
        employeeFirstJobTime:null,
        employeeGender:'0',
        employeeEmployType:null,
        employeeInHeadship:null,
        employeeEmployForm:null,
        employeeBankName:null,
        employeeEmail:null,
        employeeHeight:null,
        employeeWeight:null,
        employeeMaritalStatus:null,
        employeeBankCard:null,
        employeeIdcard:null,
        employeeCertificateTypeId:null,
        employeeCertificateCode:'',
        employeeEmergencyOnePerson:null,
        employeeEmergencyOneTel:null,
        employeeEmergencyTwoPerson:null,
        employeeEmergencyTwoTel:null,
        employeeNation:null,
        employeeParty:null,
        employeeIsTutor:null,
        employeeFormalTime:null,
        isEnable:'1',
        employeePosts:[
          {organizationSysCode:null,postSysCode:null,gradeId:null,startTime:null}
        ],
        archivesPhoto:{fileId:null},
        idcardFiles:[],
        otherCertificatesFiles:[]
      },
      rules: {
        employeeName: [
          { required: true, message: '请输入中文姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
        ],
        employeeEnglishName: [
          { min: 1, max: 30, message: '长度1-30个字母', trigger: 'blur' }
        ],
        employeeNative: [
          { required: true, message: '请选择籍贯', trigger: 'change' },
        ],
        employeeBirthday: [
          { required: true, message: '请选择出生日期', trigger: 'change' },
        ],
        employeeRegisteredType: [
          { required: true, message: '请选择户籍类型', trigger: 'change' },
        ],
        employeeJoinTime: [
          { required: true, message: '请选择入职时间', trigger: 'change' },
        ],
        employeeTel: [
          {  required: true, validator:telValidator, trigger: 'blur' }
        ],
        employeeRegisteredResidence: [
          {  required: true, message: '请输入户籍所在地', trigger: 'blur' },
          {  min: 1, max: 50, message: '长度1-50个字符', trigger: 'blur' },
        ],
        employeeFirstJobTime: [
          {  required: true, message: '请选择首次工作日期', trigger: 'change' }
        ],
        employeeGender: [
          {  required: true, message: '请选择性别', trigger: 'blur' }
        ],
        employeeEmployType: [
          {  required: true, message: '请选择聘用类型', trigger: 'blur' }
        ],
        employeeInHeadship: [
          {  required: true, message: '请选择编制类型', trigger: 'blur' }
        ],
        employeeEmployForm: [
          {  required: true, message: '请选择聘用形式', trigger: 'blur' }
        ],
        employeeBankName: [
          {  required: true, message: '请输入开户银行', trigger: 'blur' },
          {  min: 1, max: 30, message: '长度1-30个字符', trigger: 'blur' },

        ],
        employeeEmail: [
          {  required: true, validator:emailValidator, trigger: 'blur' }
        ],
        employeeHeight: [
          {required: true, validator:numValidator, trigger: 'blur' },
        ],
        employeeWeight: [
          {required: true, validator:numValidator, trigger: 'blur' },
        ],
        employeeMaritalStatus: [
          {  required: true, message: '请选择婚育状态', trigger: 'change' }
        ],
        employeeParty: [
          {  required: true, message: '请选择政治面貌', trigger: 'change' }
        ],
        employeeBankCard: [
          {  required: true, validator:bankCardValidator, trigger: 'blur' }
        ],
        employeeIdcard: [
          {  required: true, validator:idcardValidator, trigger: 'blur' }
        ],
        employeeCertificateTypeId: [
          {  required: false, message: '请选择证件类型',  trigger: 'change' }
        ],
        employeeCertificateCode: [
          {  required: false, message: '请输入证件号码', trigger: 'blur' },
          {  min: 0, max: 50,message: '长度1-50个字符', trigger: 'blur' }
        ],
        employeeEmergencyOnePerson: [
          {  required: true, message: '请输入紧急联系人1姓名', trigger: 'blur' }
        ],
        employeeEmergencyOneTel: [
          {  required: true, validator:telValidator, trigger: 'blur' }
        ],
        employeeEmergencyTwoPerson: [
          {  required: false, message: '请输入紧急联系人2姓名', trigger: 'blur' }
        ],
        employeeEmergencyTwoTel: [
          {  required: false, validator:telValidator, trigger: 'blur' }
        ],
        employeeNation: [
          {  required: true, message: '请选择民族', trigger: 'change' }
        ],
        employeeParty: [
          {  required: true, message: '请选择政治面貌', trigger: 'change' }
        ],
        employeeParty: [
          {  required: true, message: '请选择政治面貌', trigger: 'change' }
        ],
        employeeParty: [
          {  required: true, message: '请选择政治面貌', trigger: 'change' }
        ],
        employeeIsTutor: [
          {  required: true, message: '请选择是否双师', trigger: 'change' }
        ],
        employeeFormalTime: [
          {  required: false, message: '请选择转正日期', trigger: 'change' }
        ],
      },
      action:uploadUrl,
      getAllAction:uploadAndGetFileAllUrl,
      fileType:["jpg","JPG","jpeg","JPEG", "png","PNG"],
      fileSize:200,
      oldArchivesPhotoList:[],
      archivesPhotoList:[],
      oldIdcardFileList:[],
      idcardFileList:[],
      oldOtherCertificateFileList:[],
      otherCertificateFileList:[],
      headers:uploadHeaders,
    }
  },
  methods:{
    getPreData(){
      this.getNatives()
      this.getOrganizationData()
      if(this.prop.employeeId){
        this.isEdit = true
        this.getDetail()
      }
    },
    openArchivesPhotoUpload(){
      this.showUploadArchivesPhoto = true
    },
    normalizer(node) {
      return {
        id: node.organizationSysCode,
        label: node.organizationName,
        children: node.children,
      }
    },
    getDetail(){
      getDetail({employeeId:this.prop.employeeId}).then(res =>{
        let data = res.data
        let {idcardCertificate,otherIdentityCertificate,archivesPhoto,...form} = data
        this.form = form
        //设置身份证件图片回显
        let idcardFiles = idcardCertificate.files
        this.idcardFileList = idcardFiles.map(file =>{return {fileId:file.fileId,filePath:echoPrefix+file.filePath}})
        this.form.idcardFiles = idcardFiles
        // 其它身份证件回显
        let otherFiles = otherIdentityCertificate.files
        this.otherCertificateFileList = otherFiles.map(file =>{return {fileId:file.fileId,filePath:echoPrefix+file.filePath}})
        this.form.otherCertificatesFiles = otherFiles
        //设置证件照头像回显
        if(archivesPhoto){
          this.form.archivesPhoto = archivesPhoto
          this.archivesPhotoSrc = echoPrefix+archivesPhoto.filePath
        }else{
          this.form.archivesPhoto = {fileId:null}
        }
        //查询职级下拉数据用于回显
        if(this.form.employeePosts!==null && this.form.employeePosts.length>0){
          for(let i=0;i<this.form.employeePosts.length;i++){
            let ep = this.form.employeePosts[i]
            this.getGradeData(ep.postSysCode)
          }
        }
      }).catch(err =>{
        console.log('查询人员详情失败，原因：',err)
      })
    },
    getNatives(){
      getProvinceCitySelectItems().then(res =>{
        let data = res.data
        this.natives = this.handleTree(data,'provinceCityCountyCode','provinceCityCountyParentCode')
      }).catch(err =>{
        console.log('查询籍贯下拉数据失败，原因：',err)
      })
    },
    getOrganizationData(){
      getOrganizationsSelectItems().then(res =>{
        let data = res.data
        this.organizations = this.handleTree(data,'organizationId','organizationParentId')
      }).catch(err =>{
        console.log('查询组织机构下拉数据失败，原因：',err)
      })
    },
    getPostData(orgSysCode){
      getPostSelectItemsByOrganization({organizationSysCode:orgSysCode}).then(res =>{
        let data = res.data
        this.posts = data
      }).catch(err =>{
        console.log('查询岗位下拉数据失败，原因：',err)
      })
    },
    getGradeData(postSysCode){
      if(postSysCode){
        getGradeSelectItemsByPost({postSysCode:postSysCode}).then(res =>{
          let data = res.data
          this.grades = data
        }).catch(err =>{
          console.log('查询职级下拉数据失败，原因：',err)
        })
      }else{
        this.posts = []
      }
    },
    organizationChange(newOrgSysCode){
      if(newOrgSysCode){
        this.getPostData(newOrgSysCode)
      }else{
        this.posts = []
        this.grades = []
      }
    },
    postChange(newPostSysCode){
      if(newPostSysCode){
        this.getGradeData(newPostSysCode)
      }else{
        this.grades = []
      }
    },
    addEmployeePost(){
      this.form.employeePosts.push({organizationSysCode:null,postSysCode:null,gradeId:null,employForm:null,startTime:null})
    },
    delEmployeePost(index){
      this.form.employeePosts.splice(index,1)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    closeArchivesUpload(){
      this.showUploadArchivesPhoto = false
    },
    archivesUploadSuccess(res, file,fileList){
      if(res.code === 200){
        this.form.archivesPhoto.fileId = res.data.fileId
        this.archivesPhotoSrc = echoPrefix+res.data.filePath
        this.showUploadArchivesPhoto = false
      }else{
        this.$message.error('上传证件照图片失败，请稍后再试')
      }
    },
    // 身份证图片上传成功回调
    idcardUploadSuccess(res, file,fileList) {
      if(res.code === 200){
        this.form.idcardFiles.push({fileId:res.data.fileId})
        this.idcardFileList.push({fileId:res.data.fileId,filePath:echoPrefix+res.data.filePath})
      }else{
        this.$message.error('上传身份证件附件失败，请稍后再试')
      }
    },
    // 其它证件图片上传成功回调
    otherUploadSuccess(res, file,fileList) {
      if(res.code === 200){
        this.form.otherCertificatesFiles.push({fileId:res.data.fileId})
        this.otherCertificateFileList.push({fileId:res.data.fileId,filePath:echoPrefix+res.data.filePath})
      }else{
        this.$message.error('上传其它身份证件附件失败，请稍后再试')
      }
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传附件失败, 请重试");
    },
    delFile(file,fileList){
      let fileId = ''
      if(file.fileId){
        fileId = file.fileId
      }else if(this.form.fileId){
        fileId = this.form.fileId
      }else{
        fileId = null
      }

      //删除已提交文件
      if(fileId!==null){
        deleteFile({fileId:fileId}).then(res =>{
          this.form.fileId = null
          this.fileList = []
        }).catch(err =>{
          console.log('删除文件失败，原因：',err)
          this.fileList = this.oldFileList
        })
      }
    },
    downloadFile(file){
      let params = {fileId:file.fileId}
      download(params)
    },
    setFormData(){
      console.log(this.form)
      let {employeePosts,archivesPhoto,idcardFiles,otherCertificatesFiles,...employee} = this.form
      //处理二代身份证数据
      let idcardCategoryId = certificateCategory[0].value
      let idcardCertificate = {
        certificate:{
          employeeCertificateCategory:idcardCategoryId,
          employeeCertificateName:'二代居民身份证',
          employeeCertificateCode:this.form.employeeIdcard,
        },
        files:idcardFiles
      }
      //如有其它身份证件信息进行处理
      let otherCertificate = null
      if(this.form.employeeCertificateTypeId && this.form.employeeCertificateCode){
        let otherIdcardCategoryId = certificateCategory[1].value
        let oiType = this.otherIdentityTypes.find(item => item.raw.dictCode === this.form.employeeCertificateTypeId)
        let oiTypdName = oiType.raw.dictLabel
        otherCertificate = {
          certificate:{
            employeeCertificateCategory:otherIdcardCategoryId,
            employeeCertificateName:oiTypdName,
            employeeCertificateCode:this.form.employeeCertificateCode,
          },
          files:otherCertificatesFiles
        }
      }
      return {
        employee:employee,
        employeePosts:employeePosts,
        archivesPhoto:archivesPhoto,
        idcardCertificate:idcardCertificate,
        otherIdentityCertificate:otherCertificate,
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.saveLoading = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          //对表单数据进行处理
          let formData = this.setFormData()
          if (this.isEdit) {
            edit(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          } else {
            add(formData).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          }
        }else{
          this.saveLoading = false
        }
      });
      console.log('14sfsf')
    },
    // 表单重置
    reset() {
      this.form = {
        employeeName:null,
        employeeEnglishName:null,
        employeeNative:null,
        employeeBirthday:null,
        employeeRegisteredType:null,
        employeeJoinTime:null,
        employeeTel:'',
        employeeRegisteredResidence:null,
        employeeFormalTime:null,
        employeeGender:'0',
        employeeEmployType:null,
        employeeInHeadship:null,
        employeeBankName:null,
        employeeEmail:null,
        employeeHeight:null,
        employeeWeight:null,
        employeeMaritalStatus:null,
        employeeBankCard:null,
        employeeIdcard:null,
        employeeCertificateTypeId:null,
        employeeCertificateCode:'',
        employeeEmergencyOnePerson:null,
        employeeEmergencyOneTel:null,
        employeeEmergencyTwoPerson:null,
        employeeEmergencyTwoTel:null,
        employeeNation:null,
        employeeParty:null,
        isEnable:'1',
        employeePosts:[
          {organizationSysCode:null,postSysCode:null,gradeId:null,employForm:null,startTime:null,endTime:null}
        ],
        archivesPhoto:{fileId:null},
        idcardFiles:[],
        otherCertificatesFiles:[]
      };
      this.isEdit = false
    },
    cancel(){
      this.$emit('close')
      this.$destroy(this)
    },
  },
  mounted() {
    this.getPreData()
  },
}
</script>

<style scoped>
>>> .avatar-upload .el-upload--picture-card{
  width: 112px;
  height: 144px;
}
>>> .avatar-upload .el-upload--picture-card img{
  width: 110px;
  height: 144px;
}
>>> .archives-photo .el-image{
  width: 110px;
  height: 144px;
  top: 10px;
  left: -80px;
}
>>> .archives-photo-upload{
  position: relative;
  left: -75px;
}
>>> .archives-photo-form-item .el-form-item__content{
  margin-left: 30px;
}
>>> .hold-post-container{
  margin:0 20px
}
>>> .employee-post-operator{
  position: relative;
  top:36px;
}
>>> .custome-form-item-width{
  width:100%;
}
>>> .upload-archives-container .el-dialog{
  width:25vw;
}
>>> .upload-slot-img{
  width:100%;
  height: 100%;
}
</style>
